import {
  renderNumberCell,
  renderSymbolCell,
  renderTextCell
} from "@/utils/cell";
import { computed, ref, watch, type Ref } from "vue";
import { useBreakpointQuery } from "@/utils/device";
import type { PositionSchema } from "@/types/account.types";

export const usePositionTable = (
  forceCompact = false,
  selectedPositionIdModel: Ref<string | null>
) => {
  const { isSmUp, isMdUp } = useBreakpointQuery();
  // Table ref for manual control
  const tableRef = ref();
  const tableSize = computed(() => {
    if (forceCompact) {
      return "small";
    }
    if (isMdUp()) {
      return "default";
    }
    return "small";
  });

  const getPositionColumns = () => {
    const isSmallUp = forceCompact ? false : isSmUp();
    const isMediumUp = forceCompact ? false : isMdUp();
    const useCompactLabels = !isSmallUp;
    const labelProductType = isMediumUp ? "品种" : isSmallUp ? "P/T" : "";
    const labelDirection = isMediumUp ? "方向" : isSmallUp ? "LS" : "";
    const labelPnlByCost = useCompactLabels ? "逐笔" : "逐笔盈亏";
    const labelLastPrice = useCompactLabels ? "最新" : "最新价";
    const labelCost = useCompactLabels ? "成本" : "开仓成本";

    const enumMinWidth = isSmallUp ? 70 : 40;

    const columns: TableColumnList = [
      {
        label: "合约",
        prop: "symbol",
        sortable: "custom",
        align: "left",
        minWidth: 100,
        showOverflowTooltip: true,
        formatter: (row: PositionSchema) => renderSymbolCell(row.symbol)
      },
      {
        label: labelProductType,
        prop: "product_type",
        sortable: "custom",
        minWidth: enumMinWidth,
        align: "center",
        formatter: (row: PositionSchema) => {
          let text = row.product_type;
          if (!isSmallUp) {
            text = text === "期权" ? "O" : "F";
          }
          return renderTextCell(text);
        }
      },
      {
        label: labelDirection,
        prop: "direction",
        sortable: "custom",
        minWidth: enumMinWidth,
        align: "center",
        formatter: (row: PositionSchema) =>
          renderTextCell(
            row.direction,
            row.direction === "多"
              ? "text-text_red_text"
              : "text-text_green_text"
          )
      },
      {
        label: "数量",
        prop: "volume",
        sortable: "custom",
        align: "right",
        minWidth: 60,
        formatter: (row: PositionSchema) =>
          renderNumberCell(row.volume, 0, false, false)
      },
      {
        label: labelPnlByCost,
        prop: "pnl_by_cost",
        align: "right",
        minWidth: 80,
        sortable: "custom",
        showOverflowTooltip: true,
        formatter: (row: PositionSchema) =>
          renderNumberCell(row.pnl_by_cost, 1, false, true)
      },
      {
        label: labelLastPrice,
        prop: "last_price",
        sortable: "custom",
        align: "right",
        minWidth: 80,
        showOverflowTooltip: true,
        formatter: (row: PositionSchema) =>
          renderNumberCell(row.last_price, 2, false, false)
      },
      {
        label: labelCost,
        prop: "cost",
        sortable: "custom",
        align: "right",
        minWidth: 80,
        showOverflowTooltip: true,
        formatter: (row: PositionSchema) =>
          renderNumberCell(row.cost, 2, false, false)
      },
      {
        label: "保证金",
        prop: "margin",
        sortable: "custom",
        align: "right",
        minWidth: 80,
        showOverflowTooltip: true,
        formatter: (row: PositionSchema) =>
          renderNumberCell(row.margin, 2, false, false)
      }
    ];
    return columns;
  };

  const positionColumns = computed(() => getPositionColumns());

  // writable computed
  const selectedPositionId = computed({
    get: () => selectedPositionIdModel.value?.split("|")?.[2] || null,
    set: (value: PositionSchema | null) => {
      selectedPositionIdModel.value = value
        ? `${value.trade_app_name}|${value.gateway_name}|${value.vt_position_id}`
        : null;
    }
  });

  // Handle row click for toggle behavior
  const handleRowClick = (row: PositionSchema) => {
    const currentRowKey = selectedPositionId.value;
    if (currentRowKey === row.vt_position_id) {
      selectedPositionId.value = null;
    } else {
      selectedPositionId.value = row;
      tableRef.value?.getTableRef()?.setCurrentRow(row);
    }
  };

  // watch selected position id and deselect current row
  watch(selectedPositionId, newVal => {
    if (!newVal) {
      tableRef.value?.getTableRef()?.setCurrentRow();
    }
  });

  return {
    positionColumns,
    tableSize,
    selectedPositionId,
    handleRowClick,
    tableRef
  };
};
